<template>
  <div>
    <img @click="downloadPost" :src="src" />
  </div>
</template>
<script>
export default {
  data() {
    return {
      src: 'https://t7.baidu.com/it/u=4036010509,3445021118&fm=193&f=GIF',
    }
  },
  methods: {
    // 触发下载海报
    downloadPost() {
      this.downloadByBlob(this.src, '邀请海报.jpg')
    },
    // 下载图片实现
    downloadByBlob(url, name) {
      const image = new Image()
      image.setAttribute('crossOrigin', 'anonymous')
      image.src = url
      image.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const ctx = canvas.getContext('2d')
        ctx.drawImage(image, 0, 0, image.width, image.height)
        canvas.toBlob(blob => {
          const url = URL.createObjectURL(blob)
          this.download(url, name)
          // 用完释放URL对象
          URL.revokeObjectURL(url)
        })
      }
    },
    download(href, name) {
      const eleLink = document.createElement('a')
      eleLink.download = name
      eleLink.href = href
      eleLink.click()
      eleLink.remove()
    },
  },
}
</script>
